import Service from '@ember/service';
// import { inject as service } from '@ember/service';
import { service } from '@ember/service';

export default class CallService extends Service {
  @service message;
  @service loading;

  // 通用请求方法
  async doRequest(method, url, body = null, params = null, ignoreError = false) {
    try {
      this.loading.showLoading();
      
      // 处理URL参数
      let requestUrl = url;
      if (params) {
        const queryString = this.transformRequest(params);
        const separator = url.indexOf('?') === -1 ? '?' : '&';
        requestUrl = url + separator + queryString;
      }

      // 构建请求配置
      const requestConfig = {
        method: method.toUpperCase(),
        headers: {
          Authentication: sessionStorage.getItem('Authentication') || '',
        },
      };

      // 对于有body的请求，添加Content-Type
      if (body) {
        requestConfig.headers['Content-Type'] = 'application/json';
        requestConfig.body = body;
      }

      console.log('请求配置:', requestConfig); // 调试信息
      const response = await fetch(requestUrl, requestConfig);
      const res = await response.json();
      
      this.loading.completeLoading();
      
      if (!res.success) {
        console.log(`${method} error, url=${requestUrl}${body ? ', body=' + body : ''}`);
        if (!ignoreError) {
          this.message.showErrMsg(res.message);
        }
      }
      
      return res;
    } catch (e) {
      console.error(e);
      if (!ignoreError) {
        this.message.showErrMsg(e);
      }
      this.loading.completeLoading();
      return JSON.stringify({ success: false, code: 555, message: e });
    }
  }

  async post(url, body, ignoreError = false) {
    return this.doRequest('POST', url, body, null, ignoreError);
  }

  async put(url, body, ignoreError = false) {
    return this.doRequest('PUT', url, body, null, ignoreError);
  }

  async get(url, params, ignoreError = false) {
    return this.doRequest('GET', url, null, params, ignoreError);
  }

  async delete(url, params, ignoreError = false) {
    return this.doRequest('DELETE', url, null, params, ignoreError);
  }


  transformRequest(obj) {
    var str = [];
    for (var p in obj) {
      str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p]));
    }
    return str.join('&');
  }

  is_browser = typeof window == 'object';
  cacheExpireMS = 1000 * 60 * 5; // 5 minutes

  /**
   * 浏览器本地存储
   * @param key
   * @returns
   */
  async fetchCached(key, realFetch) {
    var now = new Date().getTime();
    if (this.is_browser) {
      const cached = sessionStorage[key];
      if (cached) {
        var cachedObj = JSON.parse(cached);
        var expireTime = cachedObj.expireTime;
        if (expireTime > now) {
          return cachedObj.data;
        }
      }

      try {
        const data = await realFetch();
        if (data && data.success) {
          sessionStorage[key] = JSON.stringify({
            expireTime: now + this.cacheExpireMS,
            data: data,
          });
        }
        return data;
      } catch (e) {
        console.error(e);
      }
    } else {
      return await realFetch();
    }
  }

  async getCached(url, json) {
    var w = '';

    if (json) {
      w = url.indexOf('?') == -1 ? '?' : '&';
      w = w + this.transformRequest(json);
    }
    var realUrl = url + w;

    return await this.fetchCached(realUrl, async () => this.get(realUrl, {}));
  }

  getFormData(formName) {
    var formData = {};
    var formList = document.querySelectorAll('input[form="' + formName + '"]');
    this.form2Json(formList, formData);
    var selectList = document.querySelectorAll(
      'textarea[form="' + formName + '"]',
    );
    this.form2Json(selectList, formData);

    return formData;
  }

  form2Json(form, json) {
    for (var i = 0; i < form.length; i++) {
      var formItem = form[i];
      var value = formItem.value;
      if (
        formItem.getAttribute('required') &&
        'true' == formItem.getAttribute('required') &&
        value == ''
      ) {
        throw new Error('请填写完整后提交');
      }

      var name = formItem.name || formItem.getAttribute('name');

      if (name.includes('::')) {
        //两级对象[parent::child]
        const parts = name.split('::');
        if (parts.length === 2) {
          // 处理对象结构 (例如: A::a)
          const [parent, child] = parts;
          if (!json[parent]) {
            json[parent] = {};
          }
          json[parent][child] = value;
        } else if (parts.length === 3) {
          // 处理数组结构 (例如: B::c::0)
          const [arrName, propName, indexStr] = parts;
          const index = parseInt(indexStr, 10);
          if (isNaN(index)) continue;

          if (!json[arrName]) {
            json[arrName] = [];
          }
          const arr = json[arrName];
          if (!arr[index]) {
            arr[index] = {};
          }
          arr[index][propName] = value;
        }
      } else {
        var jsonValue =
          value.startsWith('[') || value.startsWith('{')
            ? JSON.parse(value)
            : value;

        if (name in json) {
          //合并
          json[name] =
            json[name] instanceof Array
              ? [...json[name], jsonValue]
              : [json[name], jsonValue];
        } else {
          json[name] = jsonValue;
        }
      }
    }
  }

  generateUUID() {
    return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, (c) =>
      (
        c ^
        (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))
      ).toString(16),
    );
  }

  showErrMsg(msg) {
    // 创建一个自定义事件，并传递消息
    const customEvent = new CustomEvent('showMessage', {
      detail: {
        type: 'error',
        message: msg,
      },
    });

    // 触发自定义事件
    document.body.dispatchEvent(customEvent);
  }
}
